package com.wanmait.hotelManage.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wanmait.hotelManage.util.ImageUtil;

/**
 * Servlet implementation class CodeServlet
 */
@WebServlet("/CodeServlet")
public class CodeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
       

    public CodeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	// TODO Auto-generated method stub
    	doGet(request, response);
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String action = request.getParameter("action");
		
		if("code".equals(action)) {
			this.code(request, response);
		}else if("check".equals(action)) {
			this.check(request, response);
		}
	}

	

	private void check(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String code = request.getParameter("code");
		HttpSession session = request.getSession();
		String rightCode = (String)session.getAttribute("code");
		
		PrintWriter out = response.getWriter();
		
		if(code!=null && code.equalsIgnoreCase(rightCode))
		{
			//ע�ⲻҪʹ��println����Ϊ���˸�����
			out.print("ok");
		}
		else
		{
			out.print("no");
		}
		out.close();
		
	}

	private void code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		response.setContentType("image/jpeg");
		//��ֹͼ�񻺴�
		response.setHeader("Pragma","no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0); 
		HttpSession session = request.getSession();
		ImageUtil imageUtil = new ImageUtil(120, 40, 5,30);
		session.setAttribute("code", imageUtil.getCode());
		imageUtil.write(response.getOutputStream());
		
	}

	
	
	

}
